package com.ayf.payment.game.api.service.impl;

import com.ayf.payment.game.api.dto.Token;
import com.ayf.payment.game.api.service.TokenRepository;
import com.ayf.payment.game.api.service.TokenService;
import com.ayf.payment.game.api.utils.MD5Util;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author: zh-liang
 * @Date : 2020-1-7 15:36
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenRepository tokenRepository;


    @Override
    public Token createToken(Integer merchantId, Integer loginId, String loginType){
        return createToken(merchantId,loginId,loginType,"defaultIp");
    }

    @Override
    public void deleteToken(Integer merchantId) {
        tokenRepository.delete(merchantId);
    }

    @Override
    public void deleteTokenByToken(String token) {
        tokenRepository.deleteTokenByToken(token);
    }

    @Override
    public void deleteTokenByLoginId(Integer merchantId, Integer loginId) {
        tokenRepository.deleteTokenByLoginId(merchantId, loginId);
    }

    @Override
    public void deleteClientToken(Integer merchantId,String clientType) {
        tokenRepository.delete(merchantId);
    }

    @Override
    public Token createToken(Integer merchantId, Integer loginId, String loginType, String reqIp) {
        Token entity =new Token();
        entity.setMerchantId(merchantId);
        entity.setLoginId(loginId);
        entity.setLoginType(loginType);
        entity.setReqIp(reqIp);

        String accessToken = MD5Util.strToMd5(UUID.randomUUID().toString().concat(SnowFlakeUtils.getUniqueId()));
        if(loginType.equals("gateWay")){
            entity.setExpiredSeconds(TokenRepository.ACCESS_TOKEN_CLIENT_EXPIRED_SECOND);
            entity.setLoginOutTime(TokenRepository.ACCESS_TOKEN_CLIENT_EXPIRED_SECOND-20l);
        }else {
            entity.setExpiredSeconds(TokenRepository.ACCESS_TOKEN_EXPIRED_SECOND);
        }
        entity.setAccessToken(accessToken);
        entity.setRefreshToken(MD5Util.strToMd5(accessToken));
        if (tokenRepository.save(entity)){
            return entity;
        }
        return null;
    }

}
